<template>
  <div class="experiment-info" style="border-style:groove ;width: 98%" >
    <div style="font-size: 18px; font-weight: bold; color: #333; background-color:  #f5f5f5; border: 1px solid #ccc; border-radius: 5px; padding: 10px; text-align: center;">
      A#实验信息
    </div>
    <div class="child-component">
    </div>
    <el-form :model="experimentInfo" :rules="rules" ref="formRef" label-width="40%">
      <el-form-item label="实验时间">
        <el-date-picker v-model="experimentInfo.dtime" type="datetime" placeholder="选择实验时间" readonly disabled></el-date-picker>
      </el-form-item>
      <el-form-item label="产品型号" prop="pmodel">
        <el-input v-model="experimentInfo.pmodel" placeholder="请选择产品型号"></el-input>
      </el-form-item>
      <el-form-item label="炉编号">
        <el-input v-model="experimentInfo.heatNo" readonly disabled/>
      </el-form-item>
      <el-form-item label="生长编号" prop="growNo">
        <el-input v-model="experimentInfo.growNo"/>
      </el-form-item>
      <el-form-item label="催化剂批号" prop="catalystBn">
        <el-input v-model="experimentInfo.catalystBn"/>
      </el-form-item>
      <el-form-item label="催化剂目数" prop="catalystQt">
        <el-input v-model="experimentInfo.catalystQt"/>
      </el-form-item>
      <el-form-item label="催化剂投料量 (g)" prop="catalystIr">
        <el-input v-model="experimentInfo.catalystIr" type="number"/>
      </el-form-item>
      <el-form-item label="载气种类" prop="carrierT">
        <el-input v-model="experimentInfo.carrierT" placeholder=""></el-input>
      </el-form-item>
      <el-form-item label="碳源种类" prop="carbonsT">
        <el-input v-model="experimentInfo.carbonsT" placeholder=""></el-input>
      </el-form-item>
      <el-form-item label="载气密度 (g/L)" prop="carrierD">
        <el-input v-model="experimentInfo.carrierD"   @blur="formatCarrierD" type="number"/>
      </el-form-item>
      <el-form-item label="碳源密度 (g/L)" prop="carbonsD">
        <el-input t v-model="experimentInfo.carbonsD"   @blur="formatCarbonsD" type="number"/>
      </el-form-item>
      <el-form-item label="氢气密度 (g/L)" prop="hydrogenD">
        <el-input v-model="experimentInfo.hydrogenD"   @blur="formatHydrogenD" type="number"/>
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="experimentInfo.note"/>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import emitter from '@/utils/eventBus';
import {reactive, ref} from 'vue';
import type {FormInstance, FormRules} from 'element-plus';

const { proxy }: any = getCurrentInstance();
// 定义实验信息的响应式数据
const experimentInfo = ref({});
const rules = reactive<FormRules>({
  pmodel: [
    { required: true, message: '产品型号不能为空', trigger: 'blur' }
  ],
  growNo: [
    { required: true, message: '生长编号不能为空', trigger: 'blur' }
  ],
  catalystBn: [
    { required: true, message: '催化剂批号不能为空', trigger: 'blur' }
  ],
  catalystQt: [
    { required: true, message: '催化剂目数不能为空', trigger: 'blur' }
  ],
  catalystIr: [
    { required: true, message: '催化剂投料量不能为空', trigger: 'blur' }
  ],
  carrierT: [
    { required: true, message: '载气种类不能为空', trigger: 'blur' }
  ],
  carbonsT: [
    { required: true, message: '碳源种类不能为空', trigger: 'blur' }
  ],
  carrierD: [
    { required: true, message: '载气密度不能为空', trigger: 'blur' }
  ],
  carbonsD: [
    { required: true, message: '碳源密度不能为空', trigger: 'blur' }
  ],
  hydrogenD: [
    { required: true, message: '氢气密度不能为空', trigger: 'blur' }
  ]
});

const formRef = ref<FormInstance>();

async function initExperimentInfo() {
  try {
    const response = await proxy.$api.ExperimentUrl['getLast']("A");
    console.log('getLast:', response.result);

    // 检查 response 的结构，确保正确访问数据
    if (response && response.result!== null) {
      // 将接口返回的数据更新到 experimentInfo 中
      experimentInfo.value = response.result;
    } else {
      console.warn("No data received or result is null.");
    }
  } catch (error) {
    console.error("Error fetching data:", error);
  }
}

// 载气密度 (g/L)格式化函数
function formatCarrierD(event: any) {
  const inputValue = event.target.value;
  if (inputValue === '') {
    // 如果输入为空，直接返回
    experimentInfo.value.carrierD = '';
    return;
  }
  experimentInfo.value.carrierD = parseFloat(inputValue).toFixed(2);
}
// 碳源密度 (g/L)格式化函数
function formatCarbonsD(event: any) {
  const inputValue = event.target.value;
  if (inputValue === '') {
    // 如果输入为空，直接返回
    experimentInfo.value.carbonsD = '';
    return;
  }
  experimentInfo.value.carbonsD = parseFloat(inputValue).toFixed(2);
}
// 氢气密度 (g/L)格式化函数
function formatHydrogenD(event: any) {
  const inputValue = event.target.value;
  if (inputValue === '') {
    // 如果输入为空，直接返回
    experimentInfo.value.hydrogenD = '';
    return;
  }
  experimentInfo.value.hydrogenD = parseFloat(inputValue).toFixed(2);
}

// 每秒刷新一次 dtime
let timer: number;
onMounted(async () => {
  await initExperimentInfo();

  // 开启定时器
  timer = setInterval(() => {
    const now = new Date();
    console.log('Anow:', now);
    // 将当前时间转换为 ISO 格式，并将其设置为实验时间
    experimentInfo.value.dtime =new Date().toLocaleString('zh-CN', { hour12: false, timeZone: 'Asia/Shanghai' });
    experimentInfo.value.heatNo = "A";
  }, 1000);

  //
  emitter.on('getExperimentInfoAline', async (data) => {

    formRef.value?.validate(async (valid) => {
      if (valid) {
        // 表单校验通过，执行后续逻辑，这里可以添加提交数据等操作
        console.log('表单校验通过');
        emitter.emit('experimentInfoDataAline', experimentInfo.value);
      } else {
        console.log('表单校验不通过');
        emitter.emit('experimentInfoDataAline', null);
      }
    });

  });
});

// 组件卸载时清理定时器和事件监听，防止内存泄漏
onUnmounted(() => {
  clearInterval(timer);
  emitter.off('getExperimentInfoAline');
});


</script>

<style scoped>
.experiment-info {
  width: 98%;
  height: 62%;
}

.el-form-item {
  margin-bottom: 2px;
}

.el-input {
  width: 79%;
}

.el-select {
  width: 79%;
}
</style>